package com.kx.file.service.impl;

import com.kx.file.mapper.GifWorkMapper;
import com.kx.file.pojo.GifWork;
import com.kx.file.pojo.GifWorkExample;
import com.kx.file.service.GifService;
import com.kx.file.util.AlibabaOSSUtil;
import com.kx.file.util.GifUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;

import static com.kx.file.controller.FileController.FILE_PATH;

/**
 * @Author Sun
 * @Date 2021/7/22 21:06
 */
@Service
public class GifServiceImpl implements GifService {

    @Resource
    private GifWorkMapper gifWorkMapper;

    @Override
    public void addGifWork(String url) {
        GifWork gifWork = new GifWork();
        gifWork.setVideoUrl(url);
        gifWork.setState(0);
        gifWorkMapper.insertSelective(gifWork);
    }

    @Override
    public void createGif(File file, String fileName, String url) {
        GifUtil.buildGifAndJpg(file.getAbsolutePath(),5,50,10,10);
        String jpgFileName=fileName.substring(0,(fileName.lastIndexOf(".")))+".jpg";
        String gifFileName=fileName.substring(0,(fileName.lastIndexOf(".")))+".gif";
        //上传至阿里云
        String jpgUrl= AlibabaOSSUtil.uploadFile(jpgFileName,new File(FILE_PATH+File.separator+jpgFileName));
        String gifUrl=AlibabaOSSUtil.uploadFile(gifFileName,new File(FILE_PATH+File.separator+gifFileName));

        //更新数据库中的jpg和gif的url
        GifWorkExample example = new GifWorkExample();
        GifWorkExample.Criteria criteria = example.createCriteria();
        criteria.andVideoUrlEqualTo(url);
        GifWork gifWork = new GifWork();
        gifWork.setGifUrl(gifUrl);
        gifWork.setJpgUrl(jpgUrl);
        gifWork.setState(1);

        //更新数据库
        gifWorkMapper.updateByExampleSelective(gifWork, example);
    }

    @Override
    public GifWork selectByVideoUrl(String videoUrl) {
        GifWorkExample example=new GifWorkExample();
        GifWorkExample.Criteria criteria = example.createCriteria();
        criteria.andVideoUrlEqualTo(videoUrl);
        List<GifWork> gifWorks = gifWorkMapper.selectByExample(example);
        if(gifWorks!=null&&gifWorks.size()>0){
            return gifWorks.get(0);
        }
        return null;
    }

}
